package com.example.demo.controllers;

import com.example.demo.pojo.ResponseEntity;
import com.example.demo.pojo.LoginParam;
import com.example.demo.pojo.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.UUID;


@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {


    @GetMapping("/get")
    @ApiOperation(value = "根据用户ID获取用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query")
    public ResponseEntity<User> get(Long id) {

        return ResponseEntity.success(new User(id, "Tom"));
    }


    @PostMapping("/send")
    @ApiOperation(value = "发送验证码", notes = "参数类型为form，用于导入postman")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号码", paramType = "form", dataType = "String", required = true, example = "13027169611")
    })
    public ResponseEntity<String> send(String mobile, @ApiIgnore HttpSession httpSession) {
        String uuid = UUID.randomUUID().toString();
        String random = uuid.substring(0, uuid.indexOf("-"));
        httpSession.setAttribute(mobile, random);
        httpSession.setMaxInactiveInterval(90); // 有效时间90s
        return ResponseEntity.success(random);
    }


    @PostMapping("/login")
    @ApiOperation(value = "验证码登录", notes = "自动识别参数类型为body")
    public ResponseEntity<Object> login(@RequestBody LoginParam param, @ApiIgnore HttpSession httpSession) {
        String attribute = (String) httpSession.getAttribute(param.getMobile());

        if (attribute != null) {
            return ResponseEntity.success();
        }

        return ResponseEntity.error("验证码过期");
    }


}
